//
//  DDtailController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 16/4/29.
//  Copyright © 2016年 sgone. All rights reserved.
//

#import "DDtailController.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "DataSingleton.h"


@interface DDtailController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSDictionary *list;
@property(nonatomic,assign) NSInteger tag1;
@property(nonatomic,strong) UIButton *btnSure;


@property(nonatomic,strong) UIButton *btnphone2;
@property(nonatomic,strong) UIButton *btnphone1;

@end

@implementation DDtailController


//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = @"订单详情";
    self.backBtn.hidden = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self creatUI];
    
    [self creatDate];

    
    
    
}



-(void)creatDate
{

    
   
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@order_info",SERVER_ADDRESS2];
    NSDictionary *parmas = @{@"wTel" : self.dataHandler.phone ,@"uToken" :  self.dataHandler.uToken , @"order_id" : self.order_id};
    [self.manager POST:urlStr parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
    
        if ([responseObject[@"error_flag"] intValue] == 0 )
        {
            
         [MBProgressHUD hideHUDForView:self.tableView animated:YES];
         NSDictionary *dict = responseObject[@"data"][@"info"];
         self.list = [NSDictionary dictionaryWithDictionary:dict];


            
            if ([self.list[@"status"] intValue] == 7) {
                
                self.btnSure.hidden = NO;
            }
            else
            {
            
                self.btnSure.hidden = YES;
            }
            
            
        [self.tableView reloadData];
         
            
    
        }
        
        else
        {
        
          [MBProgressHUD hideHUDForView:self.tableView animated:YES];
           NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
          [self.view makeToast:str];
       
        }
        
        
  
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        [self.view makeToast:@"请检查网络"];
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
    
    }];

}

-(void)creatUI
{
   

    self.btnSure = [[UIButton alloc]initWithFrame:CGRectMake(0, ViewHeight - 54 , ViewWidth, 54)];
    self.btnSure.backgroundColor = BenSe_COLOR;
    [self.btnSure setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.btnSure.titleLabel.font = [UIFont systemFontOfSize:16/FDLaOt];
    [self.btnSure setTitle:@"确 认 发 货" forState:UIControlStateNormal];
    [self.view addSubview:self.btnSure];
    [self.btnSure addTarget:self action:@selector(sure:) forControlEvents:UIControlEventTouchUpInside];
    self.btnSure.hidden = YES;
    

    
    


}




-(void)sure:(UIButton*)sender
{
    
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    
   
//    NSInteger row = sender.tag;
    NSString *oId = [NSString stringWithFormat:@"%@",self.list[@"order_id"]];
    NSString *urlStr = [NSString stringWithFormat:@"%@order_send",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataHandler.phone , @"uToken" : self.dataHandler.uToken , @"order_id" : oId };
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"error_flag"] intValue] == 0)
        {
            
            
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [self.view makeToast:@"发货成功!"];
            //刷新当前页面，前一页面进行通知刷新
            [self creatDate];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"fahuo" object:nil];
            //通知已发货页面刷新
            
            [self.navigationController popViewControllerAnimated:YES];
            
            
        }
        else
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            [self.view makeToast:str];
            
            
            //            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            //            [alter show];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.view makeToast:@"发货失败,请检查网络!"];
    }];



}




-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;

}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{



    return [[self.list objectForKey:@"product_list"] count];
    

}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 44*3+50;


}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, 0)];
    view3.backgroundColor  = [UIColor whiteColor];
    UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, 50)];
    lbl1.backgroundColor = BACKGROUND1;
    
      NSString *title = @"";
    if ([[self.list objectForKey:@"shopName"] isKindOfClass:[NSNull class]] || [self.list objectForKey:@"shopName"] == nil)
    {
        
        title = @"";
        
        
    }
    else
    {
        title = [self.list objectForKey:@"shopName"];

    }
 
  
    lbl1.text = [NSString stringWithFormat:@"    加盟商： %@",title];
    lbl1.font = [UIFont systemFontOfSize:13/FDLaOt];
    [view3 addSubview:lbl1];
    
    
    self.btnphone2 = [self btnPhone2];
    self.btnphone2.tag = 1300;
    [view3 addSubview:self.btnphone2];
    
    
    
    UILabel *lbl12 = [[UILabel alloc]initWithFrame:CGRectMake(15, 50, ViewWidth-15, 44)];
    lbl12.text = [self.list objectForKey:@"address"];
    lbl12.font = [UIFont systemFontOfSize:12/FDLaOt];
    lbl12.textColor = [UIColor grayColor];
    [lbl12 setNumberOfLines:0];
    
    [view3 addSubview:lbl12];
    
    
    
    UILabel *lbl13 = [[UILabel alloc]initWithFrame:CGRectMake(15, 50+44, ViewWidth, 44)];
    

    NSString *type2 = self.list[@"type"];
    lbl13.text = [NSString stringWithFormat:@"送货距离:  %.2f公里(%@)",[[self.list objectForKey:@"distance"] floatValue]/1000,type2] ;
    lbl13.font = [UIFont systemFontOfSize:12/FDLaOt];
    lbl13.textColor = [UIColor grayColor];
    [view3 addSubview:lbl13];
 
    
    
    
    
    UILabel *lbl14 = [[UILabel alloc]initWithFrame:CGRectMake(15, 50+44*2, ViewWidth, 44)];
    NSString *stringDate = [NSString stringWithFormat:@"%@",[self.list objectForKey:@"order_time"]];
    int ordertime = [stringDate intValue];
    NSDate *orderdate = [[NSDate alloc]initWithTimeIntervalSince1970:ordertime];
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
    [formatter2 setDateFormat:@"yyy-MM-dd  HH:mm"];
    lbl14.text = [NSString stringWithFormat:@"下单时间:  %@",[formatter2 stringFromDate:orderdate]];
    lbl14.font = [UIFont systemFontOfSize:12/FDLaOt];
    lbl14.textColor = [UIColor grayColor];
    [view3 addSubview:lbl14];
    
    
    
    
    
    
    
    
  
    
    
    
    return view3;

}





-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{

    return 44+10+50;

}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{

    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, 50)];
    
    view2.backgroundColor = [UIColor whiteColor];
    
    UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, 44)];
    lbl1.text = @"    货款合计";
    [view2 addSubview:lbl1];
    lbl1.backgroundColor = [UIColor whiteColor];
    lbl1.font = [UIFont systemFontOfSize:13/FDLaOt];
    
    
    UILabel * lbl11 = [[UILabel alloc]initWithFrame:CGRectMake(0, 44, ViewWidth, 10)];
    lbl11.backgroundColor = BACKGROUND1;
    [view2 addSubview:lbl11];
    
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(15, 54, ViewWidth, 50)];
    
    
    if ([checkNull([self.list objectForKey:@"dealer_name"]) length] > 0)
    {
        lbl.text = [NSString stringWithFormat:@"所属代理商:%@",[self.list objectForKey:@"dealer_name"]];
    }
    else
    {
        lbl.text = @"";
    }

    
//    lbl.text = [NSString stringWithFormat:@"所属代理商:%@",[self.list objectForKey:@"dealer_name"]];
    lbl.font = [UIFont systemFontOfSize:14/FDLaOt];
    [view2 addSubview:lbl];
    
    

    
    UILabel *lbl3 = [[UILabel alloc]initWithFrame:CGRectMake(ViewWidth -80, 0, 70, 50)];
    lbl3.textColor = BenSe_COLOR;
    [view2 addSubview:lbl3];
    
    
    
    lbl3.text = [NSString stringWithFormat:@"%@元",[self.list objectForKey:@"wholesaler_amount"]];
    lbl3.textAlignment = NSTextAlignmentRight;
    lbl3.font = [UIFont systemFontOfSize:10/FDLaOt];
    
    
    
    
    //phone
    self.btnphone1 = [self btnPhone];
    [view2 addSubview:self.btnphone1];
    self.btnphone1.tag = 1200;
 
    
    
    
    return view2;

}


-(UIButton *) btnPhone
{


    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(ViewWidth -105, 64, 90, 30)];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 4.0;
    btn.layer.borderWidth = 1.0;
    btn.layer.borderColor = BenSe_COLOR.CGColor;
    [btn setTitle:@"拨打电话" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14/FDLaOt];
    [btn setTitleColor:BenSe_COLOR forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(phoneCall:) forControlEvents:UIControlEventTouchUpInside];
   
    return btn;


}


-(UIButton *) btnPhone2
{
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(ViewWidth -105, 10, 90, 30)];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 4.0;
    btn.layer.borderWidth = 1.0;
    btn.layer.borderColor = BenSe_COLOR.CGColor;
    [btn setTitle:@"拨打电话" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14/FDLaOt];
    [btn setTitleColor:BenSe_COLOR forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(phoneCall:) forControlEvents:UIControlEventTouchUpInside];
    
    return btn;

}


-(void)phoneCall:(UIButton *)sender
{

    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"是否拨打商家电话?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alter show];
    alter.tag = 111;
    self.tag1 = sender.tag;
//    NSLog(@"weqweqeqe  %d",self.tag1);
    
  


}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag==111)
    {
        
        
        
        NSString *button=[alertView buttonTitleAtIndex:buttonIndex];
        if ([button isEqualToString:@"确定"]) {
            
            if (self.tag1 == 1200) {
                
                //拨打电话
                NSString *phoneNumber = [@"tel://" stringByAppendingString:[NSString stringWithFormat:@"%@",[self.list objectForKey:@"dTel"]]];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
                
                
                
            }
            
            else
                
            {
                //拨打电话[list[tag] objectForKey:@"sTel"]
                NSString *phoneNumber = [@"tel://" stringByAppendingString:[NSString stringWithFormat:@"%@",[self.list objectForKey:@"sTel"]]];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
                
            }
            
            
        }
        else if([button isEqualToString:@"取消"])
        {
            
        }
    }
    
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{


     NSString *Cell = @"CellIdentifier";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
    
    
     if (cell == nil) {
         
         cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Cell];
         
         cell.textLabel.textColor = [UIColor grayColor];
         UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(ViewWidth /2 , 0, ViewWidth / 2/3, 44)];
         [cell addSubview:lbl];
         lbl.backgroundColor =  BACKGROUND1;
         lbl.tag = 100;
         cell.backgroundColor = BACKGROUND1;
         lbl.textColor = [UIColor grayColor];
         
         lbl.font = [UIFont systemFontOfSize:11/FDLaOt];

         
         
         UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(ViewWidth / 2/3*4  , 0, ViewWidth / 2/3, 44)];
         [cell addSubview:lbl1];
         lbl1.backgroundColor = BACKGROUND1;
          lbl1.tag = 101;
         lbl1.textColor = [UIColor grayColor];
         lbl1.font = [UIFont systemFontOfSize:11/FDLaOt];
         

         
         
         
         UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(ViewWidth / 2/3*5  , 0, ViewWidth / 2/3, 44)];
         [cell addSubview:lbl2];
         lbl2.backgroundColor = BACKGROUND1;
         lbl2.tag = 102;
         lbl2.textColor = [UIColor grayColor];
         lbl2.font = [UIFont systemFontOfSize:11/FDLaOt];
         
         
    }
    
    cell.textLabel.text = self.dict [@"product_list"][indexPath.row][@"product_name"];
    
    
    UILabel *lbl = (UILabel *)[cell viewWithTag:100];
    UILabel *lbl1 = (UILabel *)[cell viewWithTag:101];
    UILabel *lbl2 = (UILabel *)[cell viewWithTag:102];
    

    
    lbl.text = [NSString stringWithFormat:@"￥%@", [self.list objectForKey:@"product_list"][indexPath.row][@"unit_price"]] ;
    lbl1.text = [NSString stringWithFormat:@"X%@", [self.list objectForKey:@"product_list"][indexPath.row][@"product_num"]] ;
    lbl2.text = [NSString stringWithFormat:@"￥%@", [self.list objectForKey:@"product_list"][indexPath.row][@"total_price"]] ;


    
    return cell;


}


@end
